<?php

/**
 * Object representation of a User table in the database.
 */
class UserTable {
	/**
	 * Gets the user with the given username.
	 * 
	 * @param	username	Username of the user fot fetch.
	 * @return The corresponding User object or NULL if failed.
	 */
	public static function getByUsername($username) {
		// Check input:
		if (!$username) {
			return NULL;
		}
		
		// Get database connection:
		$db = Database::getDB();
		
		// Prepare statement:
		$stmt = $db->prepare("SELECT * FROM Users WHERE username = :username LIMIT 1");
		$stmt->bindParam(":username", $username);
		
		// Execute statement:
		Logger::log("UserTable", "Fetching User from DB.");
		$stmt->execute();
		$row = $stmt->fetch(PDO::FETCH_ASSOC);
		Logger::log("UserTable", "User fetched.");
		
		// Make User and return:
		$userFactory = new UserFactory();
		return $userFactory->fromRow($row);
	}
	
	
	
	/**
	 * Checks if the given username and password are in the database.
	 * 
	 * @param username Username
	 * @param password Password
	 * @return True if the username and password are correct, false otherwise.
	 */
	public static function isAuthorized($username, $password) {
		// Check input:
		if (!$username or !$password) {
			return FALSE;
		}
		
		// Get DB connection:
		$db = Database::getDB();
		
		// Prepare statement
		$stmt = $db->prepare("SELECT id FROM Users WHERE username = :username AND password = :password LIMIT 1");
		$stmt->bindValue(":username", $this->username);
		$stmt->bindValue(":password", $this->password);
		
		// Execute statement:
		Logger::log("UserTable", "Checking if user is authorized.");
		$stmt->execute();
		$row = $stmt->fetch(PDO::FETCH_ASSOC);
		Logger::log("UserTable", "Checked.");
		
		// Return result:
		if ($row["id"]) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
	
	
	
	/**
	 * Gets a user by ID.
	 * 
	 * @param userID ID of the user to fetch.
	 * @return The corresponding User object or NULL if not found.
	 */
	public static function getByID($userID) {
		// Check input:
		if (!$userID) {
			return;
		}
		
		// Get DB connection:
		$db = Database::getDB();
		
		// Prepare statement:
		$stmt = $db->prepare("SELECT * FROM Users WHERE id = :id LIMIT 1");
		$stmt->bindParam(":id", $userID);
		
		// Execute:
		Logger::log("UserTable", "Fetching user by ID.");
		$stmt->execute();
		$row = $stmt->fetch(PDO::FETCH_ASSOC);
		Logger::log("UserTable", "User fetched.");
		
		// Make and return object:
		$userFactory = new UserFactory();
		return $userFactory->fromRow($row);
	}
}